import IconApp from '@/components/icon/IconApp';
import IconBiliBili from '@/components/icon/IconBiliBili';
import IconDouyin from '@/components/icon/IconDouyin';
import IconHotRankNo1 from '@/components/icon/IconHotRankNo1';
import IconHotRankNo2 from '@/components/icon/IconHotRankNo2';
import IconHotRankNo3 from '@/components/icon/IconHotRankNo3';
import IconKuaishou from '@/components/icon/IconKuaishou';
import IconToutiao from '@/components/icon/IconToutiao';
import IconWeb from '@/components/icon/IconWeb';
import IconWeChatChannels from '@/components/icon/IconWeChatChannels';
import IconWeChatOfficialAccount from '@/components/icon/IconWeChatOfficialAccount';
import IconWeibo from '@/components/icon/IconWeibo';
import { rankRecord, rankRecordAnalysis } from '@/services/api/api-assess-month-emphasize-rank';
import { exportRankRecord } from '@/services/api/api-assess-month-emphasize-record';
import { CloudDownloadOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import {
  Alert,
  Badge,
  Button,
  Card,
  Col,
  DatePicker,
  Descriptions,
  Flex,
  message,
  Radio,
  Row,
  Space,
} from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import TableAppointSource from '../appoint/TableAppointSource';
import TableEmphasize from '../exhibition/TableExhibition';
import DetailRecord from '../record/DetailRecord';
import TableVote from '../vote/TableVote';
import RankAreaRecord from './RankAreaRecord';
import SettingRecord from './SettingRecord';

dayjs.extend(customParseFormat);
const dateFormat = 'YYYY-MM-DD';
const MonthStart = 1; // 1表示周一是一周的开始，0表示周日是一周的开始

interface RankRecordProps { }

const RankRecord: React.FC<RankRecordProps> = ({ }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const [searchParam, setSearchParamState] = useState<any>({
    dataReportTypes: ['1'],
    datahubLevelIds: ['2000'],
    // dataReleaseTimes: [
    //   dayjs().day(MonthStart).add(-1, 'Month').format(dateFormat),
    //   dayjs()
    //     .day(MonthStart + 6)
    //     .format(dateFormat),
    // ],
    dataReleaseTimes: [
      dayjs().subtract(1, 'month').set('date', 21).format(dateFormat),
      dayjs().set('date', 20).startOf('day').format(dateFormat),
    ],
  });

  const [activeKey, setActiveKey] = useState<React.Key>('1');
  const [datahubLevel, setDatahubLevelState] = useState<React.Key>('2000');

  const [recordRankAalysis, setRecordRankAalysisState] =
    useState<AssessMonthEmphasizeRankData.RecordRankAalysis>();

  const columns: ProColumns<AssessMonthEmphasizeRankData.RecordRank>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          排名
        </span>
      ),
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      align: 'center',
      render: (dom, entity, index, action) => {
        if (entity.topIndex == 1) {
          return <IconHotRankNo1 width={20} height={20} />;
        } else if (entity.topIndex == 2) {
          return <IconHotRankNo2 width={20} height={20} />;
        } else if (entity.topIndex == 3) {
          return <IconHotRankNo3 width={20} height={20} />;
        } else {
          // return <>{entity.topIndex}</>;
          // return dom;
          return (
            <Badge
              count={entity.topIndex}
              overflowCount={999}
              style={{
                padding: 0,
                // marginBlockStart: -2,
                // marginInlineStart: 4,
                fontSize: 12,
                color: '#FFF',
                backgroundColor: '#979797',
              }}
            />
          );
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          {datahubLevel == '2000' ? '媒体单位' : '区域'}
        </span>
      ),
      dataIndex: 'areaName',
      align: 'center',
      width: '150px',
      render: (dom, entity, index, action) => {
        if (datahubLevel == '2000') {
          return (
            <span
              style={{
                color: entity.isExhibition == 1 ? '#ffa500' : '',
              }}
            >
              {entity.appointSourceOrganizationNames.map((item) => item)}
            </span>
          );
        } else {
          return (
            <span
              style={{
                color: entity.isExhibition == 1 ? '#ffa500' : '',
              }}
            >
              {entity.areaName}
            </span>
          );
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          平台
        </span>
      ),
      dataIndex: 'datahubChannelName',
      align: 'center',
      width: '120px',
      render: (dom, entity, index, action) => {
        return (
          <Flex justify={'center'} align={'center'}>
            {entity?.datahubChannelNames?.map((item) => {
              let icon;
              if (item == '微信公众号') {
                icon = <IconWeChatOfficialAccount width={15} height={15} />;
              } else if (item == '微信视频号') {
                icon = <IconWeChatChannels width={15} height={15} />;
              } else if (item == '微博') {
                icon = <IconWeibo width={15} height={15} />;
              } else if (item == '抖音') {
                icon = <IconDouyin width={15} height={15} />;
              } else if (item == '今日头条') {
                icon = <IconToutiao width={15} height={15} />;
              } else if (item == '快手') {
                icon = <IconKuaishou width={15} height={15} />;
              } else if (item == '哔哩哔哩') {
                icon = <IconBiliBili width={15} height={15} />;
              } else if (item == '客户端') {
                icon = <IconApp width={15} height={15} />;
              } else if (item == '网站') {
                icon = <IconWeb width={15} height={15} />;
              }
              return icon;
            })}
          </Flex>
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          标题
        </span>
      ),
      dataIndex: 'dataName',
      align: 'center',
      ellipsis: true,
      copyable: true,
      width: '18%',
      render: (dom, entity, index, action) => (
        <div
          style={{
            textAlign: 'left',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
          }}
        >
          <DetailRecord
            entrance="record"
            id={entity.id}
            name={entity.dataName}
            onRefurbish={function (): void {
              // actionRef.current?.reloadAndRest();
            }}
            onExhibitionRefurbish={function (): void {
              actionRef.current?.reloadAndRest();
            }}
          />
        </div>
      ),
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          总分
        </span>
      ),
      dataIndex: 'totalScore',
      align: 'center',
      //sorter: true,
      width: '85px',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          阅读量/播放量
        </span>
      ),
      dataIndex: 'dataReadCount',
      align: 'center',
      // sorter: true,
      width: '85px',
      render: (dom, entity, index, action) => {
        let dataReadCount = entity.dataReadCount | 0;
        let dataPlayCount = entity.dataPlayCount | 0;
        return <span>{dataReadCount + dataPlayCount}</span>;
      },
    },
    // {
    //   title: (
    //     <span
    //       style={{
    //         color: '#99a3b7',
    //         fontSize: 12,
    //         textAlign: 'center',
    //         fontWeight: 'normal',
    //       }}
    //     >
    //       阅读量
    //     </span>
    //   ),
    //   dataIndex: 'dataReadCount',
    //   align: 'center',
    //   // sorter: true,
    //   width: '85px',
    //   render: (dom, entity, index, action) => {
    //     if (
    //       entity.datahubChannelNames.includes('微信公众号') ||
    //       entity.datahubChannelNames.includes('微博') ||
    //       entity.datahubChannelNames.includes('今日头条')
    //     ) {
    //       return <span>{entity.dataReadCount}</span>;
    //     } else {
    //       return <>-</>;
    //     }
    //   },
    // },
    // {
    //   title: (
    //     <span
    //       style={{
    //         color: '#99a3b7',
    //         fontSize: 12,
    //         textAlign: 'center',
    //         fontWeight: 'normal',
    //       }}
    //     >
    //       播放量
    //     </span>
    //   ),
    //   dataIndex: 'dataPlayCount',
    //   align: 'center',
    //   // sorter: true,
    //   width: '85px',
    //   render: (dom, entity, index, action) => {
    //     if (
    //       entity.datahubChannelNames.includes('抖音') ||
    //       entity.datahubChannelNames.includes('微信视频号')
    //     ) {
    //       return <span>{entity.dataPlayCount}</span>;
    //     } else {
    //       return <>-</>;
    //     }
    //   },
    // },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          点赞量
        </span>
      ),
      dataIndex: 'dataLikeCount',
      align: 'center',
      //sorter: true,
      width: '100px',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          转发量
        </span>
      ),
      dataIndex: 'dataCollectCount',
      align: 'center',
      //sorter: true,
      width: '100px',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          发布日期
        </span>
      ),
      dataIndex: 'dataReleaseTime',
      align: 'center',
      width: '100px',
      render: (dom, entity, index, action) => {
        return dayjs(entity.dataReleaseTime).format('YYYY-MM-DD');
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          报送日期
        </span>
      ),
      dataIndex: 'createdTime',
      align: 'center',
      width: '100px',
      render: (dom, entity, index, action) => {
        return dayjs(entity.createdTime).format('YYYY-MM-DD');
      },
    },
  ];

  const renderBadge = (count: number, active = false) => {
    return (
      <Badge
        count={count}
        overflowCount={999}
        style={{
          marginBlockStart: -2,
          marginInlineStart: 4,
          color: active ? '#1890FF' : '#999',
          backgroundColor: active ? '#E6F7FF' : '#eee',
        }}
      />
    );
  };

  return (
    <>
      <PageContainer
        header={{
          title: '传播质效-重要稿件',
          breadcrumb: {
            items: [],
          },
        }}
        extra={
          access.传播质效x配置x管理员 && [
            // <SettingRecord />,
            access.传播质效x投票x页面 && <TableVote />,
            <TableEmphasize />,
            <TableAppointSource />,
            <RankAreaRecord dataReleaseTimes={searchParam.dataReleaseTimes} />,
            <Button
              icon={<CloudDownloadOutlined />}
              type="primary"
              onClick={async () => {
                const response = await exportRankRecord({ ...searchParam });
                if (response.code === 0) {
                  message.success('导出成功');
                }
              }}
            >
              导出数据
            </Button>,
            access.传播质效x设置x填报编辑控制 && <SettingRecord />,
          ]
        }
      >
        <Card loading={recordRankAalysis == undefined}>
          <Row>
            <Col span={12}>
              <Descriptions
                size="small"
                column={3}
                title={`统计范围：${recordRankAalysis?.rangeStartDate} - ${recordRankAalysis?.rangeEndDate}`}
              >
                <Descriptions.Item label="报送总量">
                  <a>{recordRankAalysis?.dataReleaseTotal}</a>
                </Descriptions.Item>
                <Descriptions.Item label="市属媒体">
                  <a>{recordRankAalysis?.datahubLevel2000Total}</a>
                </Descriptions.Item>
                <Descriptions.Item label="区县媒体">
                  <a>{recordRankAalysis?.datahubLevel3000Total}</a>
                </Descriptions.Item>
              </Descriptions>
              <Descriptions size="small" column={3}>
                <Descriptions.Item label="好报道">
                  <a>{recordRankAalysis?.dataReportType1Total}</a>
                </Descriptions.Item>
                <Descriptions.Item label="好评论">
                  <a>{recordRankAalysis?.dataReportType2Total}</a>
                </Descriptions.Item>
                <Descriptions.Item label="好创意报道">
                  <a>{recordRankAalysis?.dataReportType3Total}</a>
                </Descriptions.Item>
              </Descriptions>
              <Descriptions size="small" column={3}>
                <Descriptions.Item label="微信公众号">
                  <a>{recordRankAalysis?.datahubChannelWxgzhTotal}</a>
                </Descriptions.Item>
                <Descriptions.Item label="微信视频号">
                  <a>{recordRankAalysis?.datahubChannelWxsphTotal}</a>
                </Descriptions.Item>
                <Descriptions.Item label="微博">
                  <a>{recordRankAalysis?.datahubChannelWbTotal}</a>
                </Descriptions.Item>
              </Descriptions>
              <Descriptions size="small" column={3}>
                <Descriptions.Item label="抖音">
                  <a>{recordRankAalysis?.datahubChannelDyTotal}</a>
                </Descriptions.Item>
                <Descriptions.Item label="今日头条">
                  <a>{recordRankAalysis?.datahubChannelJrttTotal}</a>
                </Descriptions.Item>
              </Descriptions>
              <Descriptions size="small" column={3}>
                <Descriptions.Item label="快手">
                  <a>{recordRankAalysis?.datahubChannelKsTotal}</a>
                </Descriptions.Item>
                <Descriptions.Item label="哔哩哔哩">
                  <a>{recordRankAalysis?.datahubChannelBiliBiliTotal}</a>
                </Descriptions.Item>
              </Descriptions>
              <Descriptions size="small" column={3}>
                <Descriptions.Item label="客户端">
                  <a>{recordRankAalysis?.datahubChannelKhdTotal}</a>
                </Descriptions.Item>
                <Descriptions.Item label="网站">
                  <a>{recordRankAalysis?.datahubChannelWzTotal}</a>
                </Descriptions.Item>
              </Descriptions>
            </Col>
            <Col span={12}>
              <Descriptions
                size="small"
                column={3}
                title={activeKey == 1 ? '好报道' : activeKey == 2 ? '好评论' : '好创意报道'}
              >
                <Descriptions.Item label="报送">
                  <a>{recordRankAalysis?.dataReleaseCount}</a>
                </Descriptions.Item>
                <Descriptions.Item label="市属媒体">
                  <a>{recordRankAalysis?.datahubLevel2000Count}</a>
                </Descriptions.Item>
                <Descriptions.Item label="区县媒体">
                  <a>{recordRankAalysis?.datahubLevel3000Count}</a>
                </Descriptions.Item>
              </Descriptions>
              <Descriptions size="small" column={3}>
                <Descriptions.Item label="微信公众号">
                  <a>{recordRankAalysis?.datahubChannelWxgzhCount}</a>
                </Descriptions.Item>
                <Descriptions.Item label="微信视频号">
                  <a>{recordRankAalysis?.datahubChannelWxsphCount}</a>
                </Descriptions.Item>
                <Descriptions.Item label="微博">
                  <a>{recordRankAalysis?.datahubChannelWbCount}</a>
                </Descriptions.Item>
              </Descriptions>
              <Descriptions size="small" column={3}>
                <Descriptions.Item label="抖音">
                  <a>{recordRankAalysis?.datahubChannelDyCount}</a>
                </Descriptions.Item>
                <Descriptions.Item label="今日头条">
                  <a>{recordRankAalysis?.datahubChannelJrttCount}</a>
                </Descriptions.Item>
              </Descriptions>
              <Descriptions size="small" column={3}>
                <Descriptions.Item label="快手">
                  <a>{recordRankAalysis?.datahubChannelKsCount}</a>
                </Descriptions.Item>
                <Descriptions.Item label="哔哩哔哩">
                  <a>{recordRankAalysis?.datahubChannelBiliBiliCount}</a>
                </Descriptions.Item>
              </Descriptions>
              <Descriptions size="small" column={3}>
                <Descriptions.Item label="客户端">
                  <a>{recordRankAalysis?.datahubChannelKhdCount}</a>
                </Descriptions.Item>
                <Descriptions.Item label="网站">
                  <a>{recordRankAalysis?.datahubChannelWzCount}</a>
                </Descriptions.Item>
              </Descriptions>
            </Col>
          </Row>
        </Card>
        <ProTable<AssessMonthEmphasizeRankData.RecordRank>
          columns={columns}
          actionRef={actionRef}
          rowKey="id"
          request={async (params = {}, sorter) => {
            const responseAnalysis = await rankRecordAnalysis({
              ...params,
              ...searchParam,
            });

            if (responseAnalysis.code == 0) {
              setRecordRankAalysisState(responseAnalysis.data);
            }

            const response = await rankRecord({
              ...params,
              ...searchParam,
            });
            return {
              data: response.data,
              success: true,
              total: response.data?.length,
            };
          }}
          dateFormatter="id"
          defaultSize={'small'}
          pagination={false}
          search={false}
          options={{
            density: false,
            setting: false,
          }}
          ghost
          scroll={{
            x: '1200px',
          }}
          headerTitle={
            <Alert
              message="计算公式：阅读（40%）+ 点赞（30%）+ 转发（30%）"
              type="info"
              showIcon
              style={{
                fontSize: 12,
              }}
            />
          }
          toolbar={{
            menu: {
              type: 'tab',
              activeKey: activeKey,
              items: [
                {
                  key: '1',
                  label: (
                    <span>
                      好报道
                      {renderBadge(recordRankAalysis?.dataReportType1Total, activeKey === '1')}
                    </span>
                  ),
                },
                {
                  key: '2',
                  label: (
                    <span>
                      好评论
                      {renderBadge(recordRankAalysis?.dataReportType2Total, activeKey === '2')}
                    </span>
                  ),
                },
                {
                  key: '3',
                  label: (
                    <span>
                      好创意报道
                      {renderBadge(recordRankAalysis?.dataReportType3Total, activeKey === '3')}
                    </span>
                  ),
                },
              ],
              onChange: (key) => {
                setSearchParamState({
                  ...searchParam,
                  dataReportTypes: [key],
                });
                setActiveKey(key as string);
                actionRef.current?.reloadAndRest();
              },
            },
            filter: (
              <Space>
                <Radio.Group
                  defaultValue={'2000'}
                  optionType="button"
                  buttonStyle="solid"
                  size="middle"
                  onChange={(e) => {
                    setDatahubLevelState(e.target.value);

                    setSearchParamState({
                      ...searchParam,
                      datahubLevelIds: [e.target.value],
                    });
                    actionRef.current?.reloadAndRest();
                  }}
                >
                  <Radio.Button value="2000">
                    市属媒体：{recordRankAalysis?.datahubLevel2000Count}
                  </Radio.Button>
                  <Radio.Button value="3000">
                    区县媒体：{recordRankAalysis?.datahubLevel3000Count}
                  </Radio.Button>
                </Radio.Group>
                <DatePicker.RangePicker
                  // defaultValue={[dayjs().day(MonthStart) , dayjs().day(MonthStart + 6)]}
                  defaultValue={[
                    dayjs().subtract(1, 'month').set('date', 21),
                    dayjs().set('date', 20).startOf('day'),
                  ]}
                  maxDate={dayjs()}
                  format={dateFormat}
                  variant="filled"
                  allowClear={false}
                  onChange={(dates, dateStrings) => {
                    setSearchParamState({
                      ...searchParam,
                      dataReleaseTimes: dateStrings.map((item) => item),
                    });
                    actionRef.current?.reloadAndRest();
                  }}
                />
              </Space>
            ),
          }}
        />
      </PageContainer>
    </>
  );
};
export default RankRecord;
